package com.chukun.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author chukun
 * 群发消息的服务端处理器
 */
public class NettyChatServerHandler  extends SimpleChannelInboundHandler<String> {

    /**
     *  这里必须要定义成static的，不然不会进行广播
     */
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channels.forEach(ch->{
            if(ch!=channel){
                ch.writeAndFlush("[服务器端]-"+channel.remoteAddress()+" 发送消息: "+msg+"\n");
            }else{
                ch.writeAndFlush("[自己]-"+channel.remoteAddress()+" 发送消息: "+msg+"\n");
            }
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush("[服务器]-"+channel.remoteAddress()+" 上线了\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush("[服务器]-"+channel.remoteAddress()+" 掉线了\n");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush("[服务器]-"+channel.remoteAddress()+" 加入\n");
        channels.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channels.writeAndFlush("[服务器]-"+channel.remoteAddress()+" 离开\n");
    }
}
